#include "urlItemWidget.h"
#include <QDesktopServices>
#include <QNetworkReply>
#include <QApplication>
#include <QScreen>
#include <QWindow>
#include <QMouseEvent>

UrlItemWidget::UrlItemWidget(const ClipboardItem& item, QWidget *parent)
    : QWidget(parent), item(item),
      urlLabel(new QLabel(item.getDisplayText(),this)),
      urlIconLabel(new QLabel(this)),
      titleLabel(new QLabel("链接", this)),
      copyButton(new QPushButton("", this)),
      openButton(new QPushButton("", this)),
      deleteButton(new QPushButton("", this)),
      favoriteButton(new QPushButton("",this)),
      favoriteTextLayout(new QHBoxLayout()),
      mainLayout(new QVBoxLayout(this)),
      buttonLayout(new QHBoxLayout()),
      manager(new QNetworkAccessManager(this)) // 初始化网络访问管理器
{

    //设置按钮样式
    copyButton->setStyleSheet(
                "QPushButton { "
                "image: url(:/icon/icon/copy_button.png);"
                "width: 70px;"
                "height: 30px;"
                "min-width: 70px;"
                "min-height: 30px;"
                "max-width: 70px;"
                "max-height: 30px;"
                "background-color: transparent;"
                "}"
                "QPushButton:hover { "
                "image: url(:/icon/icon/copy_button_hover.png);"
                "}"
                "QPushButton:pressed { "
                "image: url(:/icon/icon/copy_button_pressed.png);"
                "}"
                );
    deleteButton->setStyleSheet(
                "QPushButton { "
                "image: url(:/icon/icon/delete_button.png);"
                "width: 70px;"
                "height: 30px;"
                "min-width: 70px;"
                "min-height: 30px;"
                "max-width: 70px;"
                "max-height: 30px;"
                "background-color: transparent;"
                "}"
                "QPushButton:hover { "
                "image: url(:/icon/icon/delete_button_hover.png);"
                "}"
                "QPushButton:pressed { "
                "image: url(:/icon/icon/delete_button_pressed.png);"
                "}"
                );
    openButton->setStyleSheet(
                "QPushButton { "
                "image: url(:/icon/icon/open_button.png);"
                "width: 70px;"
                "height: 30px;"
                "min-width: 70px;"
                "min-height: 30px;"
                "max-width: 70px;"
                "max-height: 30px;"
                "background-color: transparent;"
                "}"
                "QPushButton:hover { "
                "image: url(:/icon/icon/open_button_hover.png);"
                "}"
                "QPushButton:pressed { "
                "image: url(:/icon/icon/open_button_pressed.png);"
                "}"
                );

    // 设置标题标签的字体和大小
    titleLabel->setStyleSheet("QLabel {font-size: 18px; font-family: 'Dengxian'; font-weight: bold;}"); // 设置标题为粗体
    titleLabel->setContentsMargins(5,5,5,0);

    // 设置文本标签的字体
    urlLabel->setStyleSheet("QLabel { font-size: 14px; font-family: 'Dengxian';}");
    urlLabel->setContentsMargins(5,0,5,0);
    urlLabel->setAlignment(Qt::AlignLeft | Qt::AlignTop); // 设置文本对齐方式
    // 添加布局放置网页icon和url
    QHBoxLayout *iconLayout = new QHBoxLayout();

    QUrl childUrl(item.getDisplayText());
    QString scheme = childUrl.scheme();  // 获取方案
    QString host = childUrl.host();       // 获取主机名

    QUrl parentUrl;
    parentUrl.setScheme(scheme);
    parentUrl.setHost(host);
    parentUrl.setPath("/");

    // 获取网站图标
    QUrl url(parentUrl.toString()+"favicon.ico");
    if (url.isValid()) {
        qDebug()<< QSslSocket::supportsSsl();
        QNetworkRequest iconRequest(url);
        QNetworkReply *iconReply = manager->get(iconRequest);
        iconReply->setParent(this);
        connect(iconReply, &QNetworkReply::finished, this, &UrlItemWidget::handleIconLoaded);
    }

    // 设置文本标签自动换行
    urlLabel->setWordWrap(true);

    // 获取主屏幕的分辨率
       QScreen *screen = QGuiApplication::primaryScreen();
       QRect screenGeometry = screen->geometry();
       int screenWidth = screenGeometry.width();
       int screenHeight = screenGeometry.height();
       urlLabel->setFixedWidth(screenWidth*0.13);
       urlLabel->setMaximumWidth(screenWidth*0.13);
       urlLabel->setMaximumHeight(screenHeight*0.10);

    iconLayout->addWidget(urlIconLabel); // 添加网页图标标签
    iconLayout->addWidget(urlLabel);   // 添加url标签

    //居中对齐
    iconLayout->setAlignment(Qt::AlignCenter);

    // 添加收藏按钮的样式设置
    QString favoriteImageUrl = item.isFavorite() ? 
        ":/icon/icon/favorite_button_pressed.png" : 
        ":/icon/icon/favorite_button.png";
        
    favoriteButton->setStyleSheet(
        "QPushButton { "
        "image: url(" + favoriteImageUrl + ");"
        "width: 15px;"
        "height: 15px;"
        "min-width: 15px;"
        "min-height: 15px;"
        "max-width: 15px;"
        "max-height: 15px;"
        "background-color: transparent;"
        "border: none;"
        "}"
    );

    // 修改布局设置
    favoriteTextLayout->addWidget(titleLabel);
    favoriteTextLayout->addStretch();
    favoriteTextLayout->addWidget(favoriteButton);

    // 修改 mainLayout 中的添加顺序
    mainLayout->addLayout(favoriteTextLayout);  // 替换原来的 mainLayout->addWidget(titleLabel);

    // 将图标布局添加到主布局中
    mainLayout->addLayout(iconLayout);

    buttonLayout->addWidget(copyButton);
    buttonLayout->addWidget(openButton);
    buttonLayout->addWidget(deleteButton);

    //button下外边距
    buttonLayout->setContentsMargins(0,0,0,5);

    // 布置按钮布局
    mainLayout->addLayout(buttonLayout);

    setLayout(mainLayout);

    this->installEventFilter(this);

    connect(copyButton, &QPushButton::clicked, this, &UrlItemWidget::onCopyClicked);
    connect(openButton, &QPushButton::clicked, this, &UrlItemWidget::onOpenClicked);
    connect(deleteButton, &QPushButton::clicked, this, &UrlItemWidget::onDeleteClicked);
    connect(favoriteButton, &QPushButton::clicked, this, &UrlItemWidget::onFavoriteClicked);
}

// 事件过滤器，用于捕获双击事件
bool UrlItemWidget::eventFilter(QObject* obj, QEvent* event) {
    if (obj == this && event->type() == QEvent::MouseButtonDblClick) {
        QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
        // 获取 mainLayout 的相对位置并转换为全局位置
        QPoint globalPos = this->mapToGlobal(mainLayout->geometry().topLeft());
        QRect mainLayoutRect(globalPos, mainLayout->geometry().size());

        // 检查双击位置是否在 mainLayout 区域内
        if (mainLayoutRect.contains(mouseEvent->globalPos())) {
            onGetDetailDoubleCliked();
            return true;  // 事件已处理
        }
    }
    return QWidget::eventFilter(obj, event);
}

ClipboardItem UrlItemWidget::getItem() const {
    return item;
}

void UrlItemWidget::onCopyClicked() {
    emit copyClicked();
}

void UrlItemWidget::onOpenClicked() {
    emit openClicked();
}

void UrlItemWidget::onDeleteClicked() {
    emit deleteClicked();
}

void UrlItemWidget::handleIconLoaded() {
    QIcon icon;
    QNetworkReply *iconReply = qobject_cast<QNetworkReply *>(sender());
    if (iconReply && iconReply->error() == QNetworkReply::NoError) {
        QByteArray data = iconReply->readAll();
        QPixmap pixmap;
        if (pixmap.loadFromData(data)) {
            urlIconLabel->setPixmap(pixmap.scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation)); // 设置图标
            iconReply->deleteLater();
            return;
        }
    }
    // 若不成功，使用默认icon
    urlIconLabel->setPixmap(QIcon(QPixmap(":/page1/images/efault_icon2.png")).pixmap(30)); // 设置默认图标
    iconReply->deleteLater();
}

void UrlItemWidget::onGetDetailDoubleCliked() {
    emit getDetailDoubleCliked();
}

void UrlItemWidget::onFavoriteClicked() {
    emit favoriteClicked();
    item.setFavorite(!item.isFavorite());  // 切换收藏状态
    updateFavoriteButtonStyle();  // 立即更新按钮样式
}

// 添加更新收藏按钮样式的方法
void UrlItemWidget::updateFavoriteButtonStyle() {
    QString favoriteImageUrl = item.isFavorite() ? 
        ":/icon/icon/favorite_button_pressed.png" : 
        ":/icon/icon/favorite_button.png";
        
    favoriteButton->setStyleSheet(
        "QPushButton { "
        "image: url(" + favoriteImageUrl + ");"
        "width: 15px;"
        "height: 15px;"
        "min-width: 15px;"
        "min-height: 15px;"
        "max-width: 15px;"
        "max-height: 15px;"
        "background-color: transparent;"
        "border: none;"
        "}"
    );
}
